package com.xmut.mall.member.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.member.dao.MemberEvaluationDao;
import com.xmut.mall.member.dto.EvaluationQueryParams;
import com.xmut.mall.member.dto.MemberEvaluationDTO;
import com.xmut.mall.member.dto.MemberEvaluationReplyDto;
import com.xmut.mall.member.entity.MemberEntity;
import com.xmut.mall.member.entity.MemberEvaluationEntity;
import com.xmut.mall.member.feign.OrderFeignService;
import com.xmut.mall.member.feign.ProductFeignService;
import com.xmut.mall.member.myenum.CommentStatusEnum;
import com.xmut.mall.member.myenum.EvaluationGradeEnum;
import com.xmut.mall.member.service.MemberEvaluationService;
import com.xmut.mall.member.service.MemberService;
import com.xmut.mall.member.utils.PageUtil;
import com.xmut.mall.member.utils.RespBean;
import com.xmut.mall.member.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MemberEvaluationServiceImpl  extends ServiceImpl<MemberEvaluationDao, MemberEvaluationEntity> implements MemberEvaluationService {

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ProductFeignService productFeignService;

    /**
     * 会员商品进行评价
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public RespBean addMemberEvaluation(MemberEvaluationDTO dto) {
        // 获取当前订单项信息
        RespBean orderItemResp = orderFeignService.getOrderItemBySn(dto.getOrderItemSn());
        if (orderItemResp.getObj()==null){
            return RespBean.error("当前订单项不存在");
        }
        OrderItemEntityVo orderItem = JSON.parseObject(JSON.toJSONString(orderItemResp.getObj()), OrderItemEntityVo.class);
        orderItem.setCommentStatus(CommentStatusEnum.FINISHED.name());

        RespBean orderResp = orderFeignService.getOrderBySn(orderItem.getOrderSn());
        if (orderResp==null){
            return RespBean.error("该订单不存在");
        }
        OrderEntityVo order = JSON.parseObject(JSON.toJSONString(orderResp.getObj()), OrderEntityVo.class);

        MemberEntity member = memberService.getById(order.getMemberId());
        if (member==null){
            return RespBean.error("用户不存在");
        }

        // 获取商品信息
        RespBean skuResp = productFeignService.getSkuInfoById(dto.getSkuId());
        if (skuResp.getObj()==null){
            return RespBean.error("商品不存在");
        }
        SkuInfoEntityVo skuInfo = JSON.parseObject(JSON.toJSONString(skuResp.getObj()), SkuInfoEntityVo.class);
        //新增用户评价
        MemberEvaluationEntity memberEvaluation = new MemberEvaluationEntity(dto, skuInfo, member, order);
        memberEvaluation.setCreateTime(new Date());
        boolean save = this.save(memberEvaluation);

        // 修改订单项的评论状态

        RespBean updateOrderItem = orderFeignService.updateOrderItem(orderItem);

        if (save && updateOrderItem.getCode()==201){
            return RespBean.success("保存成功");
        }else {
            return RespBean.error("保存失败");
        }


    }

    /**
     * 获取评论的分页数据
     * @param vo
     * @param params
     * @return
     */
    @Override
    public RespBean getEvaluationPage(PageVO vo, EvaluationQueryParams params) {
        IPage<MemberEvaluationEntity> page = this.baseMapper.getEvaluationPage(PageUtil.initPage(vo), params);
        return RespBean.success("获取成功",page);
    }

    /**
     * 根据评论ID获取评论详情
     * @param id
     * @return
     */
    @Override
    public RespBean getEvaluationDetailById(Long id) {
        MemberEvaluationEntity evaluation = this.getById(id);
        if (evaluation==null){
            return RespBean.error("评论不存在");
        }
        return RespBean.success("获取成功",new MemberEvaluationVO(evaluation));
    }

    /**
     * 回复评论
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean replyEvaluation(MemberEvaluationReplyDto dto) {
        StringBuilder replyImage = new StringBuilder();
        for (String s : dto.getReplyImage()) {
            replyImage.append(s);
            replyImage.append(",");
        }
        replyImage.deleteCharAt(replyImage.length()-1);
        UpdateWrapper<MemberEvaluationEntity> updateWrapper = Wrappers.update();
        updateWrapper.set("reply_status", true);
        updateWrapper.set("reply", dto.getReply());
        if (CharSequenceUtil.isNotEmpty(replyImage)) {
            updateWrapper.set("have_reply_image", true);
            updateWrapper.set("reply_image", replyImage.toString());
        }
        updateWrapper.eq("id", dto.getId());
        boolean update = this.update(updateWrapper);
        if (update){
            return RespBean.success("回复成功");
        }else {
            return RespBean.error("回复失败");
        }
    }

    /**
     * 修改评价状态
     * @param params
     * @return
     */
    @Override
    public RespBean updateStatus(Map<String, Object> params) {
        Long id = MapUtil.getLong(params, "id");
        String status = MapUtil.getStr(params, "status");

        boolean update = this.update(new UpdateWrapper<MemberEvaluationEntity>().set("status", status).eq("id", id));
        if (update){
            return RespBean.success("修改成功");
        }else {
            return RespBean.error("修改失败");
        }

    }

    /**
     * 获取评论数量
     * @param id
     * @return
     */
    @Override
    public RespBean getEvaluationNumber(Long id) {
        EvaluationNumberVO vo = new EvaluationNumberVO();
        List<Map<String, Object>> list = this.baseMapper.getEvaluationNumber(id);
        Integer good = 0;
        Integer moderate = 0;
        Integer worse = 0;
        for (Map<String, Object> map : list) {
            if (map.get("grade").equals(EvaluationGradeEnum.GOOD.name())) {
                good = Integer.valueOf(map.get("num").toString());
            } else if (map.get("grade").equals(EvaluationGradeEnum.MODERATE.name())) {
                moderate = Integer.valueOf(map.get("num").toString());
            } else if (map.get("grade").equals(EvaluationGradeEnum.WORSE.name())) {
                worse = Integer.valueOf(map.get("num").toString());
            }
        }
        vo.setAll(good + moderate + worse);
        vo.setGood(good);
        vo.setModerate(moderate);
        vo.setWorse(worse);
        vo.setHaveImage(this.count(new QueryWrapper<MemberEvaluationEntity>()
                .eq("have_image", 1)
                .eq("goods_id", id)));
        return RespBean.success("获取成功",vo);
    }
}
